/**
* 系统管理 角色管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model="formInline.search" placeholder="角色名称/角色描述"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border
      element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <!--      <el-table-column sortable prop="id" label="ID" width="100" visible="false">-->
      <!--      </el-table-column>-->
      <!--      <input type="hidden" v-model="hiddenId" prop="roleName"/>-->
      <!-- <el-table-column sortable prop="code" label="Code" width="240">
      </el-table-column> -->
      <el-table-column sortable prop="roleName" label="角色名称" width="160">
      </el-table-column>
      <el-table-column sortable prop="roleType" label="角色类型" width="120">
      </el-table-column>
      <el-table-column sortable prop="description" label="角色描述" width="300">
      </el-table-column>
      <el-table-column sortable prop="dateCreated" label="修改时间" width="240">
        <template slot-scope="scope">
          <div>{{ scope.row.dateCreated }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteRole(scope.$index, scope.row)">删除</el-button>
          <!--          <el-button size="mini" type="success" @click="menuAccess(scope.$index, scope.row)">菜单权限</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="名称" prop="roleName">
          <el-input size="small" v-model="editForm.roleName" auto-complete="off" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="roleType">
          <el-input size="small" v-model="editForm.roleType" auto-complete="off" placeholder="请输入角色类型"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input size="small" v-model="editForm.description" auto-complete="off" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <template>
          <el-form-item label="选择权限" prop="permissionIds">
            <el-tree :data="treeData" show-checkbox :default-checked-keys="editForm.permissionIds" node-key="id"
              :props="treeProps" v-model="checkedKeys" @check="handleCheckChange">
            </el-tree>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title"
          @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 菜单权限 -->
    <el-dialog title="菜单权限" :visible.sync="menuAccessshow" width="30%" @click='closeDialog("perm")'>
      <el-tree ref="tree" default-expand-all="" :data="RoleRight" :props="RoleRightProps"
        :default-checked-keys="checkmenu" node-key="id" show-checkbox>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="menuPermSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  permissionList,
  roleList,
  roleSave,
  RoleRightSave, roleUpdate, permissionTree, roleDeleteById
} from '../../api/userMG'

// import { permissionList } from '../../aaa/index'
import Pagination from '../../components/Pagination'
export default {
  data() {
    return {
      reloadPage: false,
      treeData: [], // 存储权限树数据
      checkedKeys: [], // 存储已经勾选的权限ID
      defaultCheckedKeys: [], // 默认选中的权限ID
      treeProps: { // 树形结构配置
        label: 'permissionName', // 显示文本的字段名
        children: 'children', // 子节点的字段名
        checkStrictly: true // 是否严格的选中模式
      },
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      menuAccessshow: false, //控制数据权限显示与隐藏
      title: '添加',
      editForm: {
        roleName: '',
        roleType: '',
        description: '',
        permissionIds: []
      },

      // rules 表单验证
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        permissionIds: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      formInline: {
        page: 1,
        pageSize: 10,
        limit: 10,
        varLable: '',
        varName: '',
        token: sessionStorage.getItem('logintoken')
      },
      // 删除
      seletedata: {
        ids: '',
        token: sessionStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      // 数据权限
      RoleRight: [],
      RoleRightProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        pageNo: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  watch: {
    'editFormVisible': function (newVal,oldVal) {
      if (newVal == false){
        // 刷新当前页面
        location.reload();
      }
    }

  },


  props: {
    // 权限列表数据
    checkList: {
      type: Array,
      required: true
    },
    // 已经勾选的权限ID数组
    checkedList: {
      type: Array,
      required: true
    }
  },
  computed: {
    // 计算属性，将已勾选的权限ID转换为字符串数组
    editFormPermissionIds() {
      return this.checkedKeys.map(id => id.toString());
    }
  },
  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
    this.getPressonTreeData()
    this.defaultCheckedKeys = this.checkedList
    this.checkedKeys = this.checkedList;
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 删除用户
    deleteRole(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除
          roleDeleteById({ "id": row.id })
            .then(res => {
              if (res.result) {
                this.$message({
                  type: 'success',
                  message: '数据已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('数据删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
    // 处理树状复选框选中节点变化
    handleCheckChange(checkedNodes, checkedKeys) {
      // 更新已选中的权限ID数组
      this.checkedKeys = checkedKeys.checkedKeys;
      console.log(checkedNodes,'checkedNodes')
      console.log(checkedKeys,'checkedKeys')
      console.log(this.checkedKeys,'this.checkedKeys')
    },
    // 递归构建权限树
    buildTree(data) {
      console.log(JSON.stringify(data),"data11111")
      return data.map(item => {
        if (item.children && item.children.length > 0) {
          return {
            id: item.id,
            permissionName: item.permissionName,
            children: this.buildTree(item.children)
          };
        } else {
          return {
            id: item.id,
            permissionName: item.permissionName
          };
        }
      });
    },
    // 获取权限树 数据
    getPressonTreeData() {
      permissionTree().then(res => {
        this.treeData = res.data
      })
    },
    // 获取角色列表
    getdata(parameter) {
      roleList(parameter)
        .then(res => {
          this.loading = false
          if (res.result == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data.list
            // 分页赋值
            this.pageparm.pageNo = res.data.pageNo
            this.pageparm.pageSize = res.data.pageSize
            this.pageparm.total = res.data.totalCount
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取角色列表失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      console.log(parm)
      this.formInline.pageNo = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.formInline.pageNo = this.pageparm.pageNo
      this.formInline.pageSize = this.pageparm.pageSize
      this.getdata(this.formInline)
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.id = row.id
        this.editForm.roleName = row.roleName
        this.editForm.roleType = row.roleType
        this.editForm.description = row.description
        this.editForm.permissionIds = row.permissionIds;
        this.defaultCheckedKeys = row.permissionIds
        this.checkedKeys = row.permissionIds
      } else {
        this.title = '添加'
        this.editForm.id = undefined
        this.editForm.roleName = ''
        this.editForm.roleType = ''
        this.editForm.description = ''
        this.editForm.permissionIds = []
        this.defaultCheckedKeys = []  // 清空默认选中的权限
        this.checkedList = []  // 清空已选中的权限
      }
      console.log(this.editForm.permissionIds, "默认选中id")
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        this.editForm.permissionIds = this.checkedKeys
        console.log(this.defaultCheckedKeys, "修改的权限defaultCheckedKeys")
        console.log(this.checkedKeys, "修改的权限checkedKeys")
        console.log(this.editForm.permissionIds, "修改的权限ids")
        if (this.editForm && this.editForm.id != undefined && this.editForm.id != 'undefined') {
          roleUpdate(this.editForm)
            .then(res => {
              this.loading = false
              if (res.result == true) {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                this.getdata(this.formInline)
                this.clearEditFormData()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
              this.editFormVisible = false
            })
            .catch(err => {
              this.loading = false
              this.$message.error('角色保存失败，请稍后再试！')
              this.editFormVisible = false
            })
        } else if (valid) {
          roleSave(this.editForm)
            .then(res => {
              this.loading = false
              if (res.result == true) {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                this.getdata(this.formInline)
                this.clearEditFormData()
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
              this.editFormVisible = false
            })
            .catch(err => {
              this.loading = false
              this.$message.error('角色保存失败，请稍后再试！')
              this.editFormVisible = false
            })
        } else {
          return false
        }
      })
      // this.reloadPage = true
    },
    // 清空editForm数据的方法
    clearEditFormData() {
      this.editForm = {
        roleName: '',
        roleType: '',
        description: '',
        permissionIds: []
      };
    },
    // 数据权限
    menuAccess: function (index, row) {
      this.menuAccessshow = true
      this.saveroleId = row.roleId
      permissionList({ pageNo: 1, pageSize: 20 })
        .then(res => {
          if (res.code === '2000') {
            this.$message({
              type: 'success',
              message: '获取权限成功'
            })
            this.changemenu(res.data.list)
            this.RoleRight = this.changeArr(res.data.list)
          } else {
            this.$message({
              type: 'info',
              message: res.data.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取权限失败，请稍后再试！')
        })
    },
    // 选中菜单
    changemenu(arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      this.checkmenu = change
    },
    // tree 递归
    changeArr(list) {
      var temptree = [],
        tree = [],
        items = []
      for (var i in list) {
        if (!temptree[list[i].id]) {
          var trow = {
            id: list[i].id,
            name: list[i].permissionName,
            open: list[i].open,
            checked: list[i].checked,
            children: []
          }
          temptree[list[i].id] = trow
          items.push(trow)
        }
        if (list[i].uid > 0) {
          temptree[list[i].id]['children'].push({
            id: list[i].id,
            name: list[i].permissionName,
            open: list[i].open,
            checked: list[i].checked,
            children: []
          })
        }
      }

      for (var j in items) {
        if (temptree[items[j].pId]) {
          temptree[items[j].pId]['children'].push(temptree[items[j].id])
        } else {
          tree.push(temptree[items[j].id])
        }
      }
      temptree = null
      items = null
      return tree
    },
    // 菜单权限-保存
    menuPermSave() {
      let parm = {
        roleId: this.saveroleId,
        moduleIds: ''
      }
      let node = this.$refs.tree.getCheckedNodes()
      let moduleIds = []
      if (node.length != 0) {
        for (let i = 0; i < node.length; i++) {
          moduleIds.push(node[i].id)
        }
        parm.moduleIds = JSON.stringify(moduleIds)
      }
      RoleRightSave(parm)
        .then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: '权限保存成功'
            })
            this.menuAccessshow = false
            this.getdata(this.formInline)
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('权限保存失败，请稍后再试！')
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
        // this.reloadPage = true
      } else if (dialog == 'perm') {
        this.menuAccessshow = false
      }
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>
